import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:hkzf/model/user.dart';
import 'package:hkzf/utils/common_toast.dart';
import 'package:hkzf/utils/dio_http.dart';
import 'package:hkzf/widgets/common_floatingactionbutton.dart';
import 'package:hkzf/widgets/common_form_item.dart';
import 'package:hkzf/widgets/common_title.dart';
import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';

class UserCenter extends StatefulWidget {
  UserCenter({Key key}) : super(key: key);

  @override
  _UserCenterState createState() => _UserCenterState();
}

class _UserCenterState extends State<UserCenter> {
  TextEditingController nickNameController = new TextEditingController();
  TextEditingController phoneController = new TextEditingController();
  final picker = ImagePicker();
  // "https://tva1.sinaimg.cn/large/006y8mN6ly1g6tbnovh8jj30hr0hrq3l.jpg";
  String nickName = '';
  String phone = '';
  String avator = '';
  bool enterPage = true;
  bool loadFail = false;
  getUserInfo() async {
    var res = await DioHttp.of(context).get('/api/v1/auth/user');
    if (res == null) {
      return;
    }
    nickName = res['data']['nickName'];
    nickNameController.text = res['data']['nickName'];
    phoneController.text = res['data']['phone'];
    avator = res['data']['avator'];
    Provider.of<UserInfo>(context, listen: false).setUserInfo(res['data']);
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    getUserInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('我的信息'),
      ),
      body: ListView(
        children: [
          CommonTitle('个人信息'),
          CommonFormItem(
            label: '头像',
            contentBuilder: (BuildContext context) {
              return GestureDetector(
                onTap: () async {
                  PickedFile pickedFile =
                      await picker.getImage(source: ImageSource.gallery);
                  if (pickedFile == null) return;

                  String path = pickedFile.path;
                  String name = path.substring(path.lastIndexOf('/') + 1);
                  FormData formData = FormData.fromMap({
                    "file": await MultipartFile.fromFile(path, filename: name),
                  });

                  var res = await DioHttp.of(context)
                      .postData('/api/v1/file/upload', params: formData);
                  if (res == null) {
                    return;
                  }
                  avator = res['data'];
                  setState(() {});
                },
                child: avator != ''
                    ? ImageAvator(
                        url: avator,
                      )
                    : NameAvator(
                        name: nickName,
                      ),
              );
            },
          ),
          CommonFormItem(
              label: '昵称',
              hintText: '请输入昵称',
              controller: nickNameController,
              textAlign: TextAlign.end),
          CommonFormItem(
              label: '手机号',
              hintText: '请输入手机号',
              controller: phoneController,
              textAlign: TextAlign.end),
        ],
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: loadFail
          ? null
          : CommonFloatingActionButton('保存', () async {
              print(nickNameController.text);
              print(phoneController.text);
              print(avator);
              var params = {
                'nickName': nickNameController.text,
                'phone': phoneController.text,
                'avator': avator,
              };
              var res = await DioHttp.of(context)
                  .post('/api/v1/auth/update', params: params);
              if (res == null) {
                return;
              }
              CommonToast.showToast(res['data']['message']);
              Provider.of<UserInfo>(context, listen: false).setUserInfo(params);
            }),
    );
  }
}

class NameAvator extends StatelessWidget {
  final String name;
  const NameAvator({
    Key key,
    @required this.name,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 48,
      padding: EdgeInsets.only(right: 10),
      child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        ClipOval(
          child: Container(
            width: 40,
            height: 40,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
            child: Text(
              name.length >= 2 ? name.substring(0, 2) : name,
              style: TextStyle(color: Colors.white, fontSize: 16),
            ),
          ),
        )
      ]),
    );
  }
}

class ImageAvator extends StatelessWidget {
  final String url;
  const ImageAvator({
    Key key,
    @required this.url,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 48,
      padding: EdgeInsets.only(right: 10),
      child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        ClipOval(
          child: CircleAvatar(
            backgroundImage: NetworkImage(url),
          ),
        )
      ]),
    );
  }
}
